/*
 * @Author: Lin Hongwei
 * @Date: 2022-10-19 16:34:09
 * @LastEditTime: 2022-10-25 23:15:08
 * @LastEditors: Lin Hongwei
 * @email: 1365755396@qq.com
 * @CSDN: https://blog.csdn.net/weixin_45429409
 * @Description: 数据库连接文件
 */
const mysql = require("mysql");
const { DB_HOST, DB_PORT, DB_USER, DB_PASSWORD, DB_DATABASE } = require('./constant')
const pool = mysql.createPool({
  host: DB_HOST,
  port: DB_PORT,
  user: DB_USER,
  password: DB_PASSWORD,
  database: DB_DATABASE
})

/**
 * @description: 通过回调函数
 */
const query1 = (sql, param, callback) => {
  pool.getConnection((err, connection) => {
    if (err) return callback(err);
    //参数内容为err,data
    connection.query(sql, param, (...args) => callback(...args).then(() => {
      connection.release()
    }))
  })
}

/**
 * @description: 通过promise
 */
const query = (sql, param) => {
  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) return reject(err);
      //参数内容为err,data
      connection.query(sql, param, (err, data) => {
        connection.release();
        if(err) return reject(err); 
        return resolve(data);
      })
    })
  })
}


const close = () => pool && pool.end()
module.exports = {
  query,
  close
}